from datetime import date, timedelta

from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from users.models import User


# 用户总量统计
class UserTotalCountView(APIView):

    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):

        # 获取数据
        count = User.objects.all().count()

        # 获取当前日期
        now_date = date.today()

        return Response({'count': count, "date": now_date})


# 日活跃用户统计
class UserDailyActiveCountView(APIView):

    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        # 获取数据
        count = User.objects.filter(last_login__gte=now_date).count()

        return Response({'count': count, "date": now_date})


# 日注册量统计
class UserDailyIncrementCountView(APIView):
    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        # 获取数据
        count = User.objects.filter(date_joined__gte=now_date).count()

        return Response({'count': count, "date": now_date})


# 日下单用户量统计
class UserDailyOrderCountView(APIView):
    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        # 获取数据
        count = User.objects.filter(orderinfo__create_time__gte=now_date).count()

        return Response({'count': count, "date": now_date})


# 月增用户统计
class UserMonthCountView(APIView):
    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()

        # 获取30天前日期
        start_date = now_date - timedelta(days=30)

        date_list = []

        for i in range(30):
            # 获取每天
            start_date = start_date + timedelta(days=1)

            # 获取第二天
            second_date = start_date + timedelta(days=1)

            # 获取数据
            count = User.objects.filter(date_joined__gte=start_date, date_joined__lt=second_date,).count()

            # 渲染数据
            date_list.append({"count": count, "date": start_date})

        return Response(date_list)



